package com.briup.smartcity_group1.web.controller.auth;

import com.briup.smartcity_group1.bean.basic.Category;
import com.briup.smartcity_group1.consts.BeanNameConsts;
import com.briup.smartcity_group1.consts.DataMessageConsts;
import com.briup.smartcity_group1.service.ICategoryService;
import com.briup.smartcity_group1.utils.result.Result;
import com.briup.smartcity_group1.web.vo.CategoryUpdateVO;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 资讯栏目模块控制器
 *
 * @author WangChen
 * @date 2023/1/6 15:05
 */
@RestController
@RequestMapping(BeanNameConsts.CATEGORY)
public class CategoryController {

    @Autowired
    private ICategoryService service;

    @GetMapping(value = "/all")
    public List<Category> getAll(){
        return service.findAll();
    }

    @GetMapping(value = "/page")
    public PageInfo<Category> getAllByPage(@RequestParam(required = true,defaultValue = "1") Integer pageNum,
                                           @RequestParam(required = true,defaultValue = "3") Integer pageSize){
        return service.pageQueryAll(pageNum,pageSize);
    }

    @PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void save(@RequestParam(required = true) String categoryDescription,
                     @RequestParam(required = true) String categoryName,
                     @RequestParam(required = true) Integer categoryOrder,
                     @RequestParam(required = false) Integer categoryParentId) {

        Category category = new Category();

        category.setCategoryDescription(categoryDescription);
        category.setCategoryName(categoryName);
        category.setCategoryOrder(categoryOrder);
        category.setCategoryParentId(categoryParentId);

        service.saveCategory(category);
        Result.setDataMessage(DataMessageConsts.CATEGORY_SAVE_SUCCESS);
    }

    @PutMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void update(CategoryUpdateVO vo){

        Category category = new Category();
        BeanUtils.copyProperties(vo,category);

        service.updateCategory(category);

        Result.setDataMessage(DataMessageConsts.CATEGORY_UPDATE_SUCCESS);
    }

    @DeleteMapping
    public void delete(@RequestParam(required = true) Integer id){
        service.deleteById(id);
        Result.setDataMessage(DataMessageConsts.CATEGORY_DELETE_SUCCESS);
    }

    @DeleteMapping(value = "/batch")
    public void batchDelete(@RequestParam(required = true) Integer[] ids){
        //将Integer数组转换为int数组
        int[] intIds = new int[ids.length];

        for (int i = 0; i < ids.length; i++) {
            intIds[i] = ids[i];
        }
        service.batchDelete(intIds);
        Result.setDataMessage(DataMessageConsts.COMMENT_DELETE_SUCCESS);

    }
}
